package com.hinner.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hinner.common.Result;
import com.hinner.entity.SysMenu;
import com.hinner.entity.SysUser;
import com.hinner.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: PengFei.He
 * @Date: 2025/1/21 22:03
 * @Function:
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {

    @Autowired
    private SysMenuService sysMenuService;


    /**
     * 查询所有菜单树信息
     * @return
     */
    @RequestMapping("/treeList")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public Result list(){
        List<SysMenu> menuList = sysMenuService.list(new QueryWrapper<SysMenu>
                ().orderByAsc("order_num"));
        Map<String, Object> map = new HashMap<>();
        map.put("treeMenu",sysMenuService.buildMenuTree(menuList));
        return Result.success(map);
    }



    /**
     * 给前端调用：根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public Result findById(@PathVariable(value = "id")Integer id){
        SysMenu sysMenu = sysMenuService.getById(id);
        return Result.success(sysMenu);
    }




    /**
     * 更新菜单、 新增菜单接口
     * @param sysMenu
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:menu:add')" + "||" + "hasAuthority('system:menu:edit')")
    public Result save(@RequestBody SysMenu sysMenu){
        if (sysMenu.getId() == null || sysMenu.getId() == -1){
            //新增
            sysMenu.setCreateTime(new Date());
            sysMenuService.save(sysMenu);
        }else {
            //更新
            sysMenu.setUpdateTime(new Date());
            sysMenuService.updateById(sysMenu);
        }
        return Result.success("操作成功");
    }
}
